package{
	import flash.errors.IOError;
	import flash.events.ErrorEvent;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.net.Socket;
	import flash.text.TextField;
	import flash.utils.ByteArray;
	
	import mx.controls.Alert;
	import mx.flash.UIMovieClip;
	
	public class Main extends UIMovieClip{
		//Port to connect to
		private const PORT:int = 7070;
		
		//Socket
		private var sckt:Socket = new Socket();
		
		//Text Field for debuggin
		private var tf:TextField = new TextField();
		
		public function Main(){
			this.addChild(tf);
			
			connectSocket();
			
			
			 
			
						
		}
		
		private function connectSocket():void{
			//Event Listener for connection
			sckt.addEventListener(Event.CONNECT, onConnect);
			//Event Listener for not being able to connect
			sckt.addEventListener(IOErrorEvent.IO_ERROR, notListening);
			//Event Listener for receiving data
			sckt.addEventListener(ProgressEvent.SOCKET_DATA, receive);
			
			//Connect to loopback
			sckt.connect("127.0.0.1", PORT);
		}
		
		/**
		 * Called when any data is received by the socket
		 */
		private function receive(e:Event):void{
			var bArray:ByteArray = new ByteArray();
			
			sckt.readBytes(bArray, 0, 0);
			tf.text = bArray.toString();
			
			
			
		}
		/**
		 * Called when there is no server socket listening
		 * for an income connection.
		 * 
		 */
		private function notListening (e:Event):void{
			Alert.show("There's no socket listening for an income connection");
			sckt = null;
		}
		/**
		 * Called when a conncetion has been made with the
		 * java server
		 */
		private function onConnect(e:Event):void {
			var bArray:ByteArray = new ByteArray();
			
			Alert.show("Connected to server");
			var str:String = new String("flash -> java 1");
			bArray.writeUTFBytes(str);
			tf.text = bArray.toString();
			sckt.writeBytes(bArray, 0, 0);
			sckt.flush();
			
			str = new String("flash -> java 2");
			bArray.writeUTFBytes(str);
			tf.text = bArray.toString();
			sckt.writeBytes(bArray, 0, 0);
			sckt.flush();
		}
	}
}